package com.ayz.gateway.core.authorization;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

/**
 * @ClassName GatewayAuthorizingRealm
 * @Description TODO: 网关鉴权领域
 *                    由当前类主要负责判断 用户登录的TOKEN是否有效
 * @Author 快乐的星球
 * @Date 2023/5/11 11:59
 * @Version 1.0
 **/
public class GatewayAuthorizingRealm extends AuthorizingRealm{
    @Override
    public Class getAuthenticationTokenClass() {
        return GatewayAuthorizingToken.class;
    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        // 暂时不做授权处理
        return null;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //当前类处理鉴权工作
        GatewayAuthorizingToken gatewayAuthorizingToken=(GatewayAuthorizingToken) authenticationToken;
        String token = gatewayAuthorizingToken.getToken();
        String channelId =gatewayAuthorizingToken.getChannelId();
        String singingKey = gatewayAuthorizingToken.getSingingKey();
        //使用JWT工具类进行解码
        try {
            JWTUtils.decode(token,singingKey);
        }catch (Exception e){
            //捕获到异常说明解码失败
            throw new AuthenticationException();
        }
        return new SimpleAuthenticationInfo(gatewayAuthorizingToken.getPrincipal(),gatewayAuthorizingToken.getCredentials(),
                this.getName());
    }
}
